package hot150;

import java.util.Arrays;

// https://leetcode.cn/problems/candy/description/?envType=study-plan-v2&envId=top-interview-150
public class q15 {

    public int candy(int[] ratings) {
        return method1(ratings, ratings.length);
    }

    /**
     * 贪心算法
     * 7 ms
     * 复杂度O(n)
     */
    public int method1(int[] ratings, int n) {
        int[]nums = new int[n];
        // 初始化赋值
        Arrays.fill(nums, 1);
        // 从左到右判断，右边大于左边，则右边的糖果数比左边多1
        for (int i = 1 ; i < n ; i++) {
            if (ratings[i] > ratings[i - 1] && nums[i] <= nums[i - 1]) {
                nums[i] = nums[i - 1] + 1;
            }
        }
        // 同理
        for (int i = n - 2 ; i >= 0 ; i--) {
            if (ratings[i] > ratings[i + 1] && nums[i] <= nums[i + 1]) {
                nums[i] = nums[i + 1] + 1;
            }
        }
        return Arrays.stream(nums).sum();
    }

    /**
     * 贪心算法
     * 2 ms
     * 复杂度O(n)
     */
    public int method2(int[] ratings, int n) {
        int ans = n;
        for (int i = 0; i < n; i++) {
            // 起点
            int start = i > 0 && ratings[i - 1] < ratings[i] ? i - 1 : i;
            // 递增
            while (i + 1 < n && ratings[i] < ratings[i + 1]) {
                i++;
            }
            // 峰顶
            int top = i;
            // 递减
            while (i + 1 < n && ratings[i] > ratings[i + 1]) {
                i++;
            }
            // 递增区间
            int inc = top - start;
            // 递减区间
            int dec = i - top;
            // 峰顶的值为递增或递增的最大长度，其余依次递减
            ans += (inc * (inc - 1) + dec * (dec - 1)) / 2 + Math.max(inc, dec);
        }
        return ans;
    }
}
